using MultiAgentsClient.Service.WorkflowEngine.BuiltInNodes;
using MultiAgentsShared;

namespace MultiAgentsClient.Service;

public class GitlabService
{
    private readonly HttpClient _httpClient;
    private readonly IEventBus _eventBus;

    public GitlabService(HttpClient httpClient)
    {
        _httpClient = httpClient;
        _eventBus = EventBus.Instance;

        _eventBus.Subscribe<NodeGitLabRequest>(async cmd => { await GetPullRequsetContent(cmd); });
    }

    public async Task GetPullRequsetContent(NodeGitLabRequest cmd)
    {
        string? gitlabToken = Environment.GetEnvironmentVariable(cmd.TokenEnvName);
        if (gitlabToken == null)
        {
            _eventBus.Publish(new NodeGitLabResponse(cmd.NodeId)
            {
                PullRequestContent = "Gitlab token environment variable have not defined.",
            });
            return;
        }

        Uri repositoryUri = new(cmd.repositoryUri);
        string baseUrl = $"{repositoryUri.Scheme}://{repositoryUri.Host}";

        string requestUri = $"{baseUrl}/api/v4/projects/{cmd.projectId}/merge_requests/{cmd.mergeRequestId}/changes";
        _httpClient.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", gitlabToken);

        try
        {
            HttpResponseMessage response = await _httpClient.GetAsync(requestUri);
            if (!response.IsSuccessStatusCode)
            {
                _eventBus.Publish(new NodeGitLabResponse(cmd.NodeId)
                {
                    PullRequestContent = "Gitlab request error. Please check the network.",
                });
                return;
            }

            string pullRequestContent = await response.Content.ReadAsStringAsync();

            _eventBus.Publish(new NodeGitLabResponse(cmd.NodeId)
            {
                PullRequestContent = pullRequestContent,
            });
        }
        catch (Exception ex)
        {
            Debug.LogError(ex.ToString());
        }


        return;
    }
}
